package com.service;

import com.dao.AddDao;
import com.dao.AdminDao;
import com.dao.impl.AddDaoImpl;
import com.dao.impl.AdminDaoImpl;
import com.entity.Users;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.jasypt.util.text.StrongTextEncryptor;

import java.util.Objects;

public class UsersService {
    private AddDao addDao;
    private PasswordEncryptor passwordEncryptor;;
    private StrongTextEncryptor textEncryptor;
    private AdminDao adminDao;
    public UsersService(){
        addDao=new AddDaoImpl();
        this.passwordEncryptor=new StrongPasswordEncryptor();
        this.textEncryptor=new StrongTextEncryptor();
        this.adminDao=new AdminDaoImpl();

    }

    public Users add(Users user) throws Exception {
        Users dbUser=addDao.getByUsername(user.getUsername());
        if(Objects.nonNull(dbUser)){
            throw new  IllegalStateException(String.format("已经存在用户名为%s的用户",user.getUsername()));
        }
        String pwdHash = user.getPwdHash();
        String s = passwordEncryptor.encryptPassword(pwdHash);
        user.setPwdHash(s);
        textEncryptor.setPassword(s);
        user.setPwhHashCode(textEncryptor.encrypt(pwdHash));
        return addDao.create(user);
    }


    public Users getByUsername(String username,String password) throws Exception {
        Users dbUsers = addDao.getByUsernameForPassword(username,password);
        return dbUsers;
    }
    public Users getByUsername(String username) throws Exception {
        Users dbUsers = addDao.getByUsername(username);
        return dbUsers;
    }
    //修改密码
    public Users modify(Users user) throws Exception {
        Users users = addDao.updatePassword(user);
        return users;
    }

    public Users updateAdmin(Users users) throws Exception {
        Users users1 = addDao.updateAdmin(users);
        return users1;
    }
}
